package com.hxd.mall.wxapi

import android.app.Activity
import android.app.Dialog
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.widget.ImageView
import com.hxd.mall.R
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.login_bind_view
import com.hxd.mall.constant.HxdConstantsAccount
import com.hxd.mall.constant.HxdConstantsAccount.isLogin
import com.hxd.mall.constant.HxdConstantsAccount.wx_login_asstoken
import com.hxd.mall.constant.HxdConstantsAccount.wx_login_flag
import com.hxd.mall.constant.HxdConstantsRouterPath.PathAccount.path_login_input_phone
import com.hxd.mall.constant.HxdConstantsRouterPath.Product.path_hxd_main_page
import com.hxd.mall.module.MainActivity
import com.hxd.mall.module.account.bean.WxLoginSuccessBean
import com.hxd.mall.module.account.login.LoginActivity
import com.hxd.mall.module.usercenter.home.MineReLoadBean
import com.hxd.mall.module.usercenter.settings.bean.SettingBean
import com.hxd.mall.network.base.BaseRequest
import com.hxd.mall.network.service.ManagerFunctionApi
import com.hxd.mall.utils.local.HxdSharePreferenceUtil
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.getStringData
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.saveStringData
import com.hxd.mall.utils.local.NavigationUtil.routerNavigation
import com.hxd.mall.utils.local.RequestUtil
import com.hxd.mall.utils.local.StackManageUtil
import com.hxd.mall.utils.local.StackManageUtil.loginOut
import com.hxd.mall.utils.local.ThirdInitUtil.weixinAppId
import com.hxd.mall.utils.open.AnimationUtil
import com.hxd.mall.utils.open.ToastUtil
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import org.greenrobot.eventbus.EventBus
import java.util.*

class WXEntryActivity : Activity(), IWXAPIEventHandler {

    private var alertDialog: Dialog? = null
    private val TAG = this.javaClass.simpleName
    private var mApi: IWXAPI? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mApi = WXAPIFactory.createWXAPI(this, weixinAppId, true)
        mApi!!.handleIntent(intent, this)
    }

    //微信发送的请求将回调到onReq方法
    override fun onReq(baseReq: BaseReq) {
    }

//    override fun onResume() {
//        super.onResume()
//        initLoadingDialog()
//    }

    //发送到微信请求的响应结果
    override fun onResp(resp: BaseResp) {
        when (resp.errCode) {
            BaseResp.ErrCode.ERR_OK -> {                //发送成功
                try {
                    val code = (resp as (SendAuth.Resp)).code
                    initLoadingDialog()
                    getAccess_token(code)
                    Log.i("wx_code", "code=$code")
                } catch (e: Exception) {
                    //从微信界面取消分享回来
                    //Log.d("wx_code", "${(resp as SendMessageToWX.Resp).errCode}")
                }
            }
            //发送取消
            BaseResp.ErrCode.ERR_USER_CANCEL -> {
            }
            //发送被拒绝
            BaseResp.ErrCode.ERR_AUTH_DENIED -> {
                ToastUtil.showToast("绑定失败")
            }
            //发送返回
            else -> {
            }
        }
        finish()
        Log.i("wx_code", "errCode=$resp.errCode")

    }


    /**
     * @param code 请求码
     */
    private fun getAccess_token(code: String) {
        val treeMap = TreeMap<String, Any>()
        treeMap["code"] = code
        treeMap["state"] = getStringData(wx_login_flag, "") ?: ""
        BaseRequest.request(
            ManagerFunctionApi.mIAccountFunctionApi.getUserWXinfo(RequestUtil.getRequestBody(treeMap)), {
                if (it.code == 0) {
                    //服务端获取信息成功
                    whichGo(it)
                } else {
                }
            },
            {
                ToastUtil.showToast(it.msg ?: "")
            })
    }

    //根据字段跳转对应界面
    private fun whichGo(it: WxLoginSuccessBean) {
        if (isLogin) {
            //如果已经登录了,不要跳转逻辑
            EventBus.getDefault().post(SettingBean())
            ToastUtil.showToast("绑定成功")
            return
        }

        when (it.data?.status) {
            "login" -> {
                it.data?.accessToken?.run {
                    //登录成功 ，保存token
                    isLogin = true
                    HxdConstantsAccount.token = this
                    saveStringData("token", this)
                    ToastUtil.showToast("登录成功")
                    //同志我的界面刷新数据
                    EventBus.getDefault().post(MineReLoadBean())

                    //StackManageUtil.closeOtherOnlyActivity(MainActivity(), path_hxd_main_page)
                    loginOut(WXEntryActivity())
                    finish()
                }
            }

            "register" -> {
                saveStringData(wx_login_flag, it.data.status)
                saveStringData("wxAccessToken", it.data.wxAccessToken)
                it?.data?.wxAccessToken?.let { it1 ->
                    saveStringData(wx_login_asstoken, it1)
                    //走注册流程->跳转到绑定手机号界面
                    StackManageUtil.removeActivity(LoginActivity())
                    routerNavigation(path_login_input_phone,mutableMapOf(login_bind_view to -1))
                }

            }
        }
    }


    private fun initLoadingDialog() {
        if (alertDialog != null && alertDialog!!.isShowing) return
        alertDialog = Dialog(this, R.style.TranslucentBackground)
        val inflater = LayoutInflater.from(this).inflate(R.layout.dialog_loading, null).apply {
            findViewById<ImageView>(R.id.iv_dialogloading_img).startAnimation(AnimationUtil.strRotation())
        }
        alertDialog?.setContentView(inflater)
        alertDialog?.setCanceledOnTouchOutside(false)
        alertDialog?.setCancelable(false)
    }


    override fun onDestroy() {
        super.onDestroy()
        alertDialog?.dismiss()
    }
}
